package org.iebrowser;

import java.util.*;
import java.io.*;

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.*;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.custom.*;
import swing2swt.layout.FlowLayout;

public class MainClass {

	protected Shell shell;
	private Text locTxt;
	Button stopBtn;
	Button goBtn;
	Button backBtn;
	Button reloadBtn;
	private CTabFolder tabFolder;
	private CTabItem addTabItem;
	private boolean doing_stuff = false;
	private Label statusBar;
	private Composite composite;
	private Button bookmarkBtn;
	private ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>();
	private Menu menu;
	private MenuItem fileMenuItem;
	private Menu fileMenu;
	private MenuItem newTabItem;
	private MenuItem exitItem;
	private MenuItem newWindowItem;
	private MenuItem toolsMenuItem;
	private Menu toolsMenu;
	private MenuItem optionsMenuItem;
	private Button homeBtn;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			MainClass window = new MainClass();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(700, 399);
		shell.setText("Browser");
		shell.setLayout(new GridLayout(7, false));
		
		backBtn = new Button(shell, SWT.NONE);
		backBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				getCurrentBrowser().back();
			}
		});
		backBtn.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.BOLD));
		backBtn.setText("  <-  ");
		
		Button forwardBtn = new Button(shell, SWT.NONE);
		forwardBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				getCurrentBrowser().forward();
			}
		});
		forwardBtn.setText("->");
		
		reloadBtn = new Button(shell, SWT.NONE);
		reloadBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				getCurrentBrowser().refresh();
			}
		});
		reloadBtn.setText("Reload");
		
		stopBtn = new Button(shell, SWT.NONE);
		stopBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				getCurrentBrowser().stop();
			}
		});
		stopBtn.setText("Stop");
		
		homeBtn = new Button(shell, SWT.NONE);
		homeBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				getCurrentBrowser().setUrl(Info.homepage);
			}
		});
		homeBtn.setText("Home");
		
		locTxt = new Text(shell, SWT.BORDER);
		locTxt.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent arg0) {
				locTxt.selectAll();
			}
		});
		locTxt.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				if (arg0.character == '\r') {
					doing_stuff = true;
					getCurrentBrowser().setUrl(locTxt.getText());
				}
			}
		});
		locTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		goBtn = new Button(shell, SWT.NONE);
		goBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				getCurrentBrowser().setUrl(locTxt.getText());
			}
		});
		
		goBtn.setText("Go");
		
		composite = new Composite(shell, SWT.NONE);
		composite.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		composite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 7, 2));
		
		bookmarkBtn = new Button(composite, SWT.NONE);
		bookmarkBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent arg0) {
				try {
					addBookmark(tabFolder.getSelection().getText(), locTxt.getText());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		bookmarkBtn.setText("Bookmark this page");
		
		tabFolder = new CTabFolder(shell, SWT.BORDER);
		tabFolder.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent arg0) {
				locTxt.setText(getCurrentBrowser().getUrl());
				if (tabFolder.getSelection() == addTabItem) {
					addTab(Info.newtabpage);
				}
			}
		});
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 7, 1));
		tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_TITLE_BACKGROUND_GRADIENT));
		tabFolder.setSimple(false);
		
		addTabItem = new CTabItem(tabFolder, SWT.NONE);
		addTabItem.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.BOLD));
		addTabItem.setText(" + ");
		
		statusBar = new Label(shell, SWT.NONE);
		statusBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 7, 1));
		statusBar.setText("Done.");		
		
		menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);
		
		fileMenuItem = new MenuItem(menu, SWT.CASCADE);
		fileMenuItem.setText("&File");
		
		fileMenu = new Menu(fileMenuItem);
		fileMenuItem.setMenu(fileMenu);
		
		newTabItem = new MenuItem(fileMenu, SWT.NONE);
		newTabItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				addTab("about:blank");
			}
		});
		newTabItem.setText("New &Tab\tControl+T");
		newTabItem.setAccelerator(SWT.CONTROL | 't');
		
		newWindowItem = new MenuItem(fileMenu, SWT.NONE);
		newWindowItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				new MainClass().open();
			}
		});
		newWindowItem.setText("&New Window\tControl+N");
		newWindowItem.setAccelerator(SWT.CONTROL | 'N');
		
		new MenuItem(fileMenu, SWT.SEPARATOR);
		
		exitItem = new MenuItem(fileMenu, SWT.NONE);
		exitItem.setAccelerator(SWT.CONTROL | 'X');
		exitItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				System.exit(0);
			}
		});
		exitItem.setText("E&xit\tControl+X");
		
		toolsMenuItem = new MenuItem(menu, SWT.CASCADE);
		toolsMenuItem.setText("&Tools");
		
		toolsMenu = new Menu(toolsMenuItem);
		toolsMenuItem.setMenu(toolsMenu);
		
		optionsMenuItem = new MenuItem(toolsMenu, SWT.NONE);
		optionsMenuItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				showOptions();
			}
		});
		optionsMenuItem.setText("&Options");
		try {
			loadSettings();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		addTab(Info.homepage);
		try {
			reloadBookmarks();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void loadSettings() throws FileNotFoundException, IOException {
		Properties p = new Properties();
		p.load(new FileInputStream("settings.txt"));
		Info.homepage = p.getProperty("homepage");
		Info.newtabpage = p.getProperty("newtabpage");
	}
	
	public Browser getCurrentBrowser() {
		Browser b = (Browser) tabFolder.getSelection().getControl();
		System.out.println(b); //#DEBUG
		return b;
	}
	
	public void addTab(String url) {
		final CTabItem ct = new CTabItem(tabFolder, SWT.CLOSE);
		final Browser b = new Browser(tabFolder, SWT.NONE);
		ct.setControl(b);
		tabFolder.setSelection(ct);
		b.addTitleListener(new TitleListener(){

			@Override
			public void changed(TitleEvent arg0) {
				ct.setText((arg0.title.length() <= 35 ? arg0.title : arg0.title.subSequence(0, 32) + "..."));
				locTxt.setText(b.getUrl());
			}});
		b.addStatusTextListener(new StatusTextListener(){

			@Override
			public void changed(StatusTextEvent arg0) {
				statusBar.setText(arg0.text);
			}});
		b.addOpenWindowListener(new OpenWindowListener(){

			@Override
			public void open(WindowEvent arg0) {
				final CTabItem ct = new CTabItem(tabFolder, SWT.CLOSE);
				final Browser b = new Browser(tabFolder, SWT.NONE);
				ct.setControl(b);
				tabFolder.setSelection(ct);
				initialize(b, ct);
				arg0.browser = b;
				
			}});
		b.setUrl(url);
	}
	
	public void initialize(final Browser b, final CTabItem ct) {
		b.addTitleListener(new TitleListener(){

			@Override
			public void changed(TitleEvent arg0) {
				ct.setText((arg0.title.length() <= 35 ? arg0.title : arg0.title.subSequence(0, 32) + "..."));
				locTxt.setText(b.getUrl());
			}});
		b.addStatusTextListener(new StatusTextListener(){

			@Override
			public void changed(StatusTextEvent arg0) {
				statusBar.setText(arg0.text);
			}});
		b.addOpenWindowListener(new OpenWindowListener(){

			@Override
			public void open(WindowEvent arg0) {
				final CTabItem ct1 = new CTabItem(tabFolder, SWT.CLOSE);
				final Browser b1 = new Browser(tabFolder, SWT.NONE);
				ct1.setControl(b1);
				tabFolder.setSelection(ct1);
				initialize(b1, ct1);
				arg0.browser = b1;
				
			}});
	}
	
	public void reloadBookmarks() throws IOException {
		java.io.BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream("bookmarks.txt")));
		while (true) {
			String s = br.readLine();
			if (s == null) break;
			Bookmark b = Bookmark.fromString(s);
			if (b == null) {
				new FileOutputStream("error.txt").write(("ERROR: bookmark file is corrupted.").getBytes());
				return;
			}
			bookmarks.add(b);
		}
		for (int i = 0; i < bookmarks.size(); i++) {
			final int d = i;
			Button b1 = new Button(composite, SWT.NONE);
			b1.setText(bookmarks.get(i).getTitle());
			b1.addMouseListener(new MouseAdapter(){
				@Override
				public void mouseDown(MouseEvent arg0) {
					getCurrentBrowser().setUrl(bookmarks.get(d).getUrl());
				}
			});
		}
	}
	
	public void addBookmark(String title, String url) throws IOException {
		new FileOutputStream("bookmarks.txt", true).write(
				(System.getProperty("line.separator") + new Bookmark(title, url).toString()).getBytes());
		reloadBookmarks();
	}
	
	public void showOptions() {
		final CTabItem ct = new CTabItem(tabFolder, SWT.CLOSE);
		ct.setText("Options");
		Group c = new Group(tabFolder, SWT.NONE);
		ct.setControl(c);
		c.setLayout(new GridLayout());
		Group grpHomePage = new Group(c, SWT.NONE);
		GridData gd_grpHomePage = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
		grpHomePage.setLayoutData(gd_grpHomePage);
		grpHomePage.setText("Home Page");
		grpHomePage.setLayout(new GridLayout(1, false));
		
		final Text text = new Text(grpHomePage, SWT.BORDER);
		text.setToolTipText("Home page address");
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		Button saveBtn = new Button(c, SWT.NONE);
		saveBtn.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseDown(MouseEvent m) {
				Info.homepage = text.getText();
				ct.dispose();
			}
		});
		saveBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		saveBtn.setText("Save");
		
		Button cancelBtn = new Button(c, SWT.NONE);
		cancelBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		cancelBtn.setText("Cancel");
		cancelBtn.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseDown(MouseEvent m) {
				ct.dispose();
			}
		});
		
		
		tabFolder.setSelection(ct);
	}
}
//http://subclipse.tigris.org/update_1.8.x
//Aq7GW8ZX6Vj3